package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_language

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.liveData
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_user.BpUser
import com.bp.hearthealth.pulse.lnapps.base.BpBaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * @author isnoam
 * @package_name LanguageViewModel
 * @description：
 */
class BpLanguageViewModel(private val repository: BpLanguageRepository) : BpBaseViewModel() {

    private var _userId = MutableLiveData<String>()
    private var _languageUserId = MutableLiveData<String>()
    var userBeanResult = MutableLiveData<BpUser?>()

    fun userBean(userId: String) {
        _userId.value = userId
    }

    data class UserDataAndLanguage(
        val userResult: Result<BpUser?>, val languageCodes: List<LanguageAndCity>
    )

    val userBeanAndLanguage: LiveData<UserDataAndLanguage> = _userId.switchMap { userId ->
        liveData {
            val userResult = try {
                val userResult = repository.requestUserBean(userId)
                UserDataAndLanguage(
                    Result.success(userResult), repository.getLanguageAndCity()
                )
            } catch (e: Exception) {
                UserDataAndLanguage(
                    Result.failure<BpUser>(e), repository.getLanguageAndCity()
                )
            }
            emit(userResult)
        }
    }

    fun insertUser(userId: String) {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                userBeanResult.value = repository.insertUser(userId)
            } catch (e: Exception) {
                userBeanResult.value = null
            }
        }
    }

    private var updateLanguage_ = MutableLiveData<RequestParam>()

    inner class RequestParam(val userId: String, val languageId: Int)

    fun updateLanguage(userId: String, languageId: Int) {
        updateLanguage_.value = RequestParam(userId, languageId)
    }

    val updateLanguage = updateLanguage_.switchMap {
        liveData {
            val resutlt = try {
                val userResult = repository.updateLanguageInfo(it.userId, it.languageId)
                Result.success(userResult)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(resutlt)
        }
    }

    fun getLanguageId(userId: String) {
        _languageUserId.value = userId
    }

    val languageId = _languageUserId.switchMap {
        liveData {
            val resutlt = try {
                val userResult = repository.getLanguagePosition(_languageUserId.value!!)
                Result.success(userResult)
            } catch (e: Exception) {
                Result.failure(e)
            }
            emit(resutlt)
        }
    }
}
